package ui;

import session.Session;

import javax.swing.*;
import java.awt.*;

public class RegisterDialog extends JDialog {
    private JTextField usernameField;
    private JPasswordField passwordField;

    public RegisterDialog(JFrame parent) {
        super(parent, "用户注册", true);
        setSize(300, 180);
        setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        panel.add(new JLabel("用户名:"));
        usernameField = new JTextField();
        panel.add(usernameField);

        panel.add(new JLabel("密码:"));
        passwordField = new JPasswordField();
        panel.add(passwordField);

        JButton confirmButton = new JButton("确认");
        confirmButton.addActionListener(e -> {
            String username = usernameField.getText().trim();
            String password = new String(passwordField.getPassword()).trim();
            // 注册普通用户
            int level = security.auth.UserManager.NORMAL_LEVEL;

            // 输入验证
            if (username.isEmpty() || password.isEmpty()) {
                JOptionPane.showMessageDialog(this,
                    "用户名和密码不能为空",
                    "注册错误",
                    JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 调用UserManager注册
            if (security.auth.UserManager.createUser(username, password, level)) {
                JOptionPane.showMessageDialog(this,
                    "用户 " + username + " 注册成功！\n权限级别: 普通用户",
                    "注册成功",
                    JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } else {
                JOptionPane.showMessageDialog(this,
                    "注册失败: 用户名可能已存在",
                    "注册错误",
                    JOptionPane.ERROR_MESSAGE);
            }
        });

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(e -> dispose());

        panel.add(confirmButton);
        panel.add(cancelButton);

        add(panel);
        setVisible(true);
    }
}

